//
//  SearchContacts.m
//  HappyStore
//
//  Created by 点点充 on 16/1/19.
//  Copyright © 2016年 LLJ. All rights reserved.
//

#import "SearchContacts.h"
#import "searchContactsCell.h"
#import "thirdPersonVC.h"
@interface SearchContacts ()<UITableViewDelegate>
{
    NSMutableArray *_aryInfo;
    NSMutableArray * dataArr;
    NSInteger paggge;
    
    NSMutableDictionary *muDicParameters;
    
    NSString *strProjectId;
}
// 数据源
@property (strong, nonatomic) NSDictionary * dataDict;
//@property (strong, nonatomic) NSMutableArray * dataArr;
@end
static NSString * searchContactscell = @"searchContactsCell";
@implementation SearchContacts

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    self.tabBarController.tabBar.hidden = YES;

    
    // 注册
    UINib * nib = [UINib nibWithNibName:@"searchContactsCell" bundle:nil];
    [self.mainTableView registerNib:nib forCellReuseIdentifier:searchContactscell];
    
    // 设置回调（一旦进入刷新状态，就调用target的action，也就是调用self的loadMoreData方法）
    MJRefreshAutoGifFooter *footer = [MJRefreshAutoGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    
    // 设置刷新图片
    UIImage *images = [UIImage imageNamed:@"mj_footer"];
    NSArray *refreshingImages = @[images];
    [footer setImages:refreshingImages forState:MJRefreshStateRefreshing];
    [footer setTitle:@"没有更多内容了" forState:MJRefreshStateRefreshing];
    footer.stateLabel.font = [UIFont systemFontOfSize:12.0f];
    footer.stateLabel.textColor = [UIColor colorWithWhite:0.6 alpha:1.0f];
    
    [footer setAutomaticallyRefresh:NO];
    
    _mainTableView.mj_footer = footer;
    
    _mainTableView.mj_footer.hidden = NO;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    UIBarButtonItem *rightBar = [[UIBarButtonItem alloc] initWithTitle:@"筛选" style:UIBarButtonItemStyleDone target:self action:@selector(btnClickRight)];
//    self.navigationItem.rightBarButtonItem = rightBar;
    //设置导航栏title的字体大小等
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:19.0f],NSFontAttributeName,[UIColor whiteColor],NSForegroundColorAttributeName, nil]];
    
    self.title = self.titleStr;
    
    dataArr = [NSMutableArray array];
    paggge = 1;
    
    _mainTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        if (dataArr.count != 0) {
            NSString *path = [[NSBundle mainBundle]pathForResource:@"refresh"
                                                            ofType:@"wav"];
            SystemSoundID soundID;
            AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:path], &soundID);
            AudioServicesPlaySystemSound(soundID); //仅播放音频
            paggge = 1;
            [muDicParameters setObject:@"1" forKey:@"page"];
            
            [self startSearch];
        }else {
            [_mainTableView.mj_header endRefreshing];
        }
    }];
    
    

    if (muDicParameters == nil) {
        muDicParameters = [NSMutableDictionary dictionary];
        [muDicParameters setObject:@"1" forKey:@"page"];
    }
    
    [self showRoundProgressWithTitle:@"请稍后..."];
    [self startSearch];
    
    self.mainSearchBar.layer.borderWidth = 1.f;
    self.mainSearchBar.layer.borderColor = [RGB(235, 235, 235) CGColor];
    
    //开启侧滑
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
    
}

-(void)loadMoreData{

    paggge += 1;
    [muDicParameters setObject:[NSString stringWithFormat:@"%ld",(long)paggge] forKey:@"page"];
    [self startSearch];

}

/**
 *  @author LLJ, 16-01-16 17:01:06
 *
 *  rightBarClick
 */
- (void)btnClickRight
{
    //取消显示后退键文字
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleDone target:nil action:nil];
    self.navigationItem.backBarButtonItem = barButtonItem;
    
//    [self performSegueWithIdentifier:@"pushSearchPriceShaiXuan" sender:self];
    

}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    if (dataArr.count != 0) {
        dataArr = [NSMutableArray array];
        [_mainTableView reloadData];
    }
    return YES;
}

- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar
{
    NSLog(@"%@",searchBar.text);
    
    if (searchBar.text.length == 0) {
        return YES;
    }else {
        paggge = 1;
        muDicParameters = [NSMutableDictionary dictionary];
        [muDicParameters setObject:[NSString stringWithFormat:@"%ld",(long)paggge] forKey:@"page"];//页码
        [muDicParameters setObject:searchBar.text forKey:@"mhName"];//类型
        [muDicParameters setObject:@"name" forKey:@"type"];
        [self startSearch];
        return YES;
    }
    
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    NSLog(@"-----%@",searchBar.text);
    if (searchBar.text.length != 0) {
        [searchBar resignFirstResponder];
        paggge = 1;
        muDicParameters = [NSMutableDictionary dictionary];
        [muDicParameters setObject:[NSString stringWithFormat:@"%ld",(long)paggge] forKey:@"page"];//页码
        [muDicParameters setObject:searchBar.text forKey:@"mhName"];//类型
        [muDicParameters setObject:@"name" forKey:@"type"];
        [self startSearch];
    }
    
    
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    [tableView tableViewDisplayWitMsg:@"没有查询到相对应的数据" ifNecessaryForRowCount:dataArr.count];

    return dataArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if (section == 0) {
        return 0;
        
    }else{
    
    return 10;
        
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{

    return 0;

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    searchContactsCell *cell = [_mainTableView dequeueReusableCellWithIdentifier:searchContactscell forIndexPath:indexPath];
    
    NSDictionary * dict = dataArr[indexPath.section];
    
    cell.lineView.hidden = YES;
    
    [cell.headImg sd_setImageWithURL:[NSURL URLWithString:dict[@"headPhoto"]]];
    [cell.headImg.layer setCornerRadius:(cell.headImg.frame.size.height/2)];
    [cell.headImg.layer setMasksToBounds:YES];
    [cell.headImg setContentMode:UIViewContentModeScaleAspectFill];
    [cell.headImg setClipsToBounds:YES];
    cell.headImg.layer.shadowColor = [UIColor whiteColor].CGColor;
    cell.headImg.layer.shadowOffset = CGSizeMake(4, 4);
    cell.headImg.layer.shadowOpacity = 0.5;
    cell.headImg.layer.shadowRadius = 2.0;
    
    if ([dict[@"userName"] isEqualToString:@""] || [dict[@"userName"] isEqualToString:@"null"]) {
        cell.nameLabel.text = dict[@"account"];
    }else{
        cell.nameLabel.text = dict[@"userName"];
    }
    

    CGSize size = [cell.nameLabel sizeThatFits:CGSizeMake(MAXFLOAT, 21)];
    if (size.width<190) {
        [cell.nameLabel setFrame:CGRectMake(cell.nameLabel.x, cell.nameLabel.y, size.width, cell.nameLabel.height)];
    }else{
        [cell.nameLabel setFrame:CGRectMake(cell.nameLabel.x, cell.nameLabel.y, 168, cell.nameLabel.height)];
    }
    
    cell.lineView.x = cell.nameLabel.x + cell.nameLabel.width + 2;
    
    
    if ([dict[@"positionName"] isEqualToString:@""] || [dict[@"positionName"] isEqualToString:@"null"]) {
        cell.posName.text = @"";
    }else{
        cell.posName.text = dict[@"positionName"];
    }
    CGSize posSize = [cell.posName sizeThatFits:CGSizeMake(MAXFLOAT, 21)];
    if (posSize.width <= 60) {
        cell.posName.width = posSize.width;
    }else{
        cell.posName.width = 60;
    }
    
    cell.posName.x = cell.lineView.x;
    cell.vImg.x = cell.posName.x + cell.posName.width + 2;
    
    if (cell.vImg.x > 185) {
        cell.vImg.x = 184;
    }
    
    
    cell.lineview.hidden = YES;
    //上级
    cell.detailLabel.text = [UsedTool userType:dict[@"userType"] companyName:dict[@"companyName"] userAddress:dict[@"userAddress"]];
//    if ([dict[@"authState"]integerValue] != 2) {
//        cell.vImg.image = [UIImage imageNamed:@"weirenzheng"];
//    }else if ([dict[@"authState"]integerValue] == 2){
//        cell.vImg.image = [UIImage imageNamed:@"yirenzheng"];
//    }
    //认证
    cell.isAuthState.hidden = [UsedTool authStateImageViewHidden:dict[@"authState"]];
    //会员图标
    cell.vImg.image = [UsedTool setVipimage:dict[@"vipLevel"]];

    return cell;
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];//取消选中状态
    
    //取消显示后退键文字
//    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleDone target:nil action:nil];
//    self.navigationItem.backBarButtonItem = barButtonItem;
//    
//    
//    ThirdPerson_Person *person = [self.storyboard instantiateViewControllerWithIdentifier:@"thirdPerson"];
//    person.strUserId = dataArr[indexPath.row][@"userId"];
//    person.strUserType = @"1";//个人
//    person.strUserName = [NSString stringWithFormat:@"%@的详情",dataArr[indexPath.row][@"userName"]];
//    [self.navigationController pushViewController:person animated:YES];
    
    if (allConstMemberid) {
        
        NSDictionary * dict = dataArr[indexPath.section];
        
        NSString * str = [USER_DEFAULTS objectForKey:@"userid"];
        NSInteger userid = [str integerValue];
        
        NSString * str1 = dict[@"userId"];
        NSInteger userId = [str1 integerValue];
        
        if (userid != userId) {
            
            thirdPersonVC * thirdPerson = [[thirdPersonVC alloc]init];
            thirdPerson.userType = dict[@"userType"];
            thirdPerson.userId = dict[@"userId"];
            
            [self.navigationController pushViewController:thirdPerson animated:YES];
        
        }
        
    }else{
    
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"请先登录" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"登录", nil];
        [alert show];
    
    }
    
    
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {
        //登录
        UIStoryboard *LoginAndRegister = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        UINavigationController *loginNAV = [LoginAndRegister instantiateViewControllerWithIdentifier:@"LoginNav"];
        [self presentViewController:loginNAV animated:YES completion:nil];
    }
    
    
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
//    // segue.identifier：获取连线的ID
//    if ([segue.identifier isEqualToString:@"price_detail"]) {
//        SearchPrice_Detail *result = segue.destinationViewController;
//        result.fundsId = strProjectId;
//    }
}


- (void)startSearch
{
    //page=页码&type=0 类型：0-查询全部 name-根据用户名或者账号&mhName=模糊查询内容
//    [SVProgressHUD showWithStatus:@"搜索中..."];
    NSString * str;
    
    if ([self.titleStr isEqualToString:@"找项目源"]) {
        
        str = @"PeopleProject_app_people.im";
    }else if ([self.titleStr isEqualToString:@"找投资人"]){
        
        str = @"PeopleFunds_app_people.im";
        
    }else if ([self.titleStr isEqualToString:@"找企业"]){
        
        str = @"getCompany_app_people.im";
        
    }else if ([self.titleStr isEqualToString:@"同行"]){

        [muDicParameters setObject:self.industry forKey:@"industry"];
        
        str = @"PeopleTonghang_app_people.im";
        
    }else if ([self.titleStr isEqualToString:@"同城"]){
        
        
        [muDicParameters setObject:[USER_DEFAULTS objectForKey:@"address"] forKey:@"address"];
        str = @"PeopleFellowCity_app_people.im";
        
    }else if ([self.titleStr isEqualToString:@"找老乡"]){
        
        [muDicParameters setObject:[USER_DEFAULTS objectForKey:@"address"] forKey:@"address"];
        str = @"PeopleFellowCity_app_people.im";
    }
    
    NSString *strURl = [NSString stringWithFormat:@"%@%@",URL_DEFINE,str];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager POST:strURl parameters:muDicParameters progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
        self.dataDict = dicInfo[@"data"];
//        NSString * jsonStr = [LSHttpTool DataTOjsonString:dicInfo];
//        NSLog(@"--------------------json:%@",jsonStr);

        if ([[dicInfo objectForKey:@"result"] integerValue] == 1) {
            
            if (paggge == 1) {
                
                 dataArr = [NSMutableArray arrayWithArray:self.dataDict[@"record"]];
                for (NSDictionary *dict in dataArr) {
                    NSString * str = [USER_DEFAULTS objectForKey:@"userid"];
                    NSInteger userid = [str integerValue];
                    NSString * str1 = dict[@"userId"];
                    NSInteger userId = [str1 integerValue];
                    if (userid == userId) {
                        [dataArr removeObject:dict];
                    }
                    
                }
                if (dataArr.count == 10) {
                    _mainTableView.mj_footer.hidden = NO;
                }else {
                    _mainTableView.mj_footer.hidden = YES;
                }
                
            }else {

                NSArray *arr = _dataDict[@"record"];
                NSMutableArray * mtArr = [NSMutableArray array];
                for (NSDictionary * dict in dataArr) {
                    [mtArr addObject:dict];
                }
                for (NSDictionary * dict in arr) {
                    [mtArr addObject:dict];
                }
                dataArr = nil;
                dataArr = mtArr;
                for (NSDictionary *dict in dataArr) {
                    NSString * str = [USER_DEFAULTS objectForKey:@"userid"];
                    NSInteger userid = [str integerValue];
                    NSString * str1 = dict[@"userId"];
                    NSInteger userId = [str1 integerValue];
                    if (userid == userId) {
                        [dataArr removeObject:dict];
                    }
                    
                }
                
            }
            
 
            [_mainTableView reloadData];
            [_mainTableView.mj_header endRefreshing];
            [_mainTableView.mj_footer endRefreshing];
            [self hideBubble];
           
        }else {
            [_mainTableView reloadData];
            [_mainTableView.mj_header endRefreshing];
            [_mainTableView.mj_footer endRefreshing];

            [self showSingleIconBubble:[dicInfo objectForKey:@"msg"]];

        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [_mainTableView.mj_header endRefreshing];
        [_mainTableView.mj_footer endRefreshing];

        [self showSingleIconBubble:error.localizedDescription];

    }];
}


@end
